
package com.xin.di.uav.applet.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.*;

public class WXPayUtil {
    private static final String CHARSET = "UTF-8";

    // 生成随机字符串
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    // 生成MD5签名
    public static String generateSignature(Map<String, String> data, String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);

        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) continue;
            if (data.get(k).trim().length() > 0) {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        return DigestUtils.md5Hex(sb.toString().getBytes(CHARSET)).toUpperCase();
    }

    // XML转Map
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        // 预处理：去除BOM头和首尾空白

        strXML = strXML.trim().replaceAll("^\\s+", "").replaceAll("\\s+$", "");
        // 创建包含XML处理逻辑的
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringElementContentWhitespace(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        try (InputStream is = new ByteArrayInputStream(strXML.getBytes(CHARSET))) {
            Document doc = builder.parse(is);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            Map<String, String> data = new HashMap<>();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    data.put(node.getNodeName(), node.getTextContent().trim());
                }
            }
            return data;
        }
    }

    // Map转XML
    public static String mapToXml(Map<String, String> data) throws Exception {
        StringWriter writer = new StringWriter();
        writer.write("<xml>");
        for (String key : data.keySet()) {
            writer.write("<" + key + ">" + data.get(key) + "</" + key + ">");
        }
        writer.write("</xml>");
        return writer.toString();
    }

    // 验证签名
    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
        if (!data.containsKey("sign")) return false;
        String sign = data.get("sign");
        return generateSignature(data, key).equals(sign);
    }
}
